package com.yiwei.zxp.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.yiwei.zxp.BussinessMainActivity;
import com.yiwei.zxp.R;
import com.yiwei.zxp.activity.SureOrderActivity;
import com.yiwei.zxp.adapter.ExpandableListAdapter;
import com.yiwei.zxp.adapter.ShopCartShiXiaoAdapter;
import com.yiwei.zxp.adapter.UpdateView;
import com.yiwei.zxp.api.Api;
import com.yiwei.zxp.api.bean.FavoriteAddBean;
import com.yiwei.zxp.api.bean.GoodBean;
import com.yiwei.zxp.api.bean.ShopDeleteBean;
import com.yiwei.zxp.event.ShopCartEvent;
import com.yiwei.zxp.util.Arith;
import com.yiwei.zxp.util.Dialog;
import com.yiwei.zxp.util.Network;
import com.yiwei.zxp.util.RxLifeUtil;
import com.yiwei.zxp.util.ToastUtil;
import com.yiwei.zxp.util.UI;
import com.yiwei.zxp.view.NestedExpandaleListView;
import com.yiwei.zxp.view.SmoothCheckBox;
import com.yiwei.zxp.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 18-5-25.
 */

public class ShopCartFragment extends BaseFragment implements UpdateView {
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.img_empty)
    ImageView imgEmpty;
    @BindView(R.id.txt_empty)
    TextView txtEmpty;
    @BindView(R.id.btn_go_shop)
    SuperButton btnGoShop;


    @BindView(R.id.expandableListView)
    NestedExpandaleListView mExpandableListView;
    @BindView(R.id.cb_select_all)
    SmoothCheckBox mCbSelectAll;
    @BindView(R.id.tv_transport)
    TextView tvTransport;
    @BindView(R.id.tv_all_money)
    TextView mTvAllMoney;
    @BindView(R.id.btn_settlement)
    SuperButton mBtnBuy;
    //    Unbinder unbinder;

    GoodBean goodBean;
    StringBuffer stringBuffer;
    @BindView(R.id.refresh)
    SwipeRefreshLayout refresh;
    @BindView(R.id.layout_empty)
    LinearLayout layoutEmpty;
    @BindView(R.id.layout_buy)
    LinearLayout layoutBuy;
    @BindView(R.id.cb_select_all_sec)
    SmoothCheckBox cbSelectAllSec;
    @BindView(R.id.btn_add_collection)
    SuperButton btnAddCollection;
    @BindView(R.id.btn_delete)
    SuperButton btnDelete;
    @BindView(R.id.layout_edit)
    LinearLayout layoutEdit;
    @BindView(R.id.layout_total)
    LinearLayout layoutTotal;
    Unbinder unbinder;
    @BindView(R.id.txt_shixiao_num)
    TextView txtShixiaoNum;
    @BindView(R.id.btn_clear_shixiao)
    TextView btnClearShixiao;
    @BindView(R.id.list_shixiao)
    RecyclerView listShixiao;
    @BindView(R.id.layout_shixiao)
    LinearLayout layoutShixiao;
    private boolean is_need_load;
    private ExpandableListAdapter mAdapter;
    private ShopCartShiXiaoAdapter shopCartShiXiaoAdapter;
    private List<GoodBean.ContentBean.GoodDetailBean> shixiaoList = new ArrayList<>();

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_shopping_cart;
    }

    @Override
    protected void initView() {
        shopCartShiXiaoAdapter = new ShopCartShiXiaoAdapter(getContext());
        listShixiao.setAdapter(shopCartShiXiaoAdapter);
        listShixiao.setNestedScrollingEnabled(false);


        mExpandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                return true;
            }
        });
        //用于列表滑动时，EditText清除焦点，收起软键盘
        mExpandableListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int scrollState) {
                if (SCROLL_STATE_TOUCH_SCROLL == scrollState) {
                    InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Activity
                            .INPUT_METHOD_SERVICE);
                    View focusView = getActivity().getCurrentFocus();
                    if (focusView != null) {
                        inputMethodManager.hideSoftInputFromWindow(focusView.getWindowToken(), InputMethodManager
                                .HIDE_NOT_ALWAYS);
                        focusView.clearFocus();
                    }
                }


            }

            @Override
            public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                View firstView = absListView.getChildAt(firstVisibleItem);
                if (firstVisibleItem == 0 && (firstView == null || firstView.getTop() == 0)) {
                    refresh.setEnabled(true);
                } else
                    refresh.setEnabled(false);
            }
        });
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getShopList();
            }
        });
        EventBus.getDefault().register(this);

    }


    private void selectAll() {
        int allCount = goodBean.getAllCount();
        double allMoney = goodBean.getAllMoney();
        if (!mCbSelectAll.isChecked()) {
            goodBean.setAllSelect(true);
            for (int i = 0; i < goodBean.getContent().size(); i++) {
                goodBean.getContent().get(i).setIsSelected(true);
                goodBean.getContent().get(i).setIsOneSelect(true);
                for (int n = 0; n < goodBean.getContent().get(i).getGoodDetail().size(); n++) {
                    if (!goodBean.getContent().get(i).getGoodDetail().get(n).isSelected()) {
                        allCount++;
//                        allMoney += Double.valueOf(goodBean.getContent().get(i).getGoodDetail().get(n).getCount())
//                                * Double.valueOf(goodBean.getContent().get(i).getGoodDetail().get(n).getPrice());
                        allMoney = Arith.add(allMoney,
                                Arith.mul(Double.valueOf(goodBean.getContent().get(i).getGoodDetail().get(n).getCount()), Double.valueOf(goodBean.getContent().get(i).getGoodDetail().get(n).getPrice())));
                        goodBean.getContent().get(i).getGoodDetail().get(n).setIsSelected(true);
                    }
                }
            }
        } else {
            goodBean.setAllSelect(false);
            for (int i = 0; i < goodBean.getContent().size(); i++) {
                goodBean.getContent().get(i).setIsSelected(false);
                goodBean.getContent().get(i).setIsOneSelect(false);
                for (int n = 0; n < goodBean.getContent().get(i).getGoodDetail().size(); n++) {
                    goodBean.getContent().get(i).getGoodDetail().get(n).setIsSelected(false);
                }
                allCount = 0;
                allMoney = 0;
            }
        }
        goodBean.setAllMoney(allMoney);
        goodBean.setAllCount(allCount);
        update(goodBean.isAllSelect(), allCount, allMoney);
        mAdapter.notifyDataSetChanged();
    }

    private void selectAllSec() {
        int allCount = goodBean.getAllCount();
        double allMoney = goodBean.getAllMoney();
        if (!cbSelectAllSec.isChecked()) {
            goodBean.setAllSelect(true);
            for (int i = 0; i < goodBean.getContent().size(); i++) {
                goodBean.getContent().get(i).setIsSelected(true);
                goodBean.getContent().get(i).setIsOneSelect(true);
                for (int n = 0; n < goodBean.getContent().get(i).getGoodDetail().size(); n++) {
                    if (!goodBean.getContent().get(i).getGoodDetail().get(n).isSelected()) {
                        allCount++;
                        allMoney = Arith.add(allMoney,
                                Arith.mul(Double.valueOf(goodBean.getContent().get(i).getGoodDetail().get(n).getCount()), Double.valueOf(goodBean.getContent().get(i).getGoodDetail().get(n).getPrice())));

                        goodBean.getContent().get(i).getGoodDetail().get(n).setIsSelected(true);
                    }
                }
            }
        } else {
            goodBean.setAllSelect(false);
            for (int i = 0; i < goodBean.getContent().size(); i++) {
                goodBean.getContent().get(i).setIsSelected(false);
                goodBean.getContent().get(i).setIsOneSelect(false);
                for (int n = 0; n < goodBean.getContent().get(i).getGoodDetail().size(); n++) {
                    goodBean.getContent().get(i).getGoodDetail().get(n).setIsSelected(false);
                }
                allCount = 0;
                allMoney = 0;
            }
        }
        goodBean.setAllMoney(allMoney);
        goodBean.setAllCount(allCount);
        update(goodBean.isAllSelect(), allCount, allMoney);
        mAdapter.notifyDataSetChanged();
    }

//    @Override
//    protected void lazyLoad() {
//        super.lazyLoad();
//        getShopList();
//    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(ShopCartEvent event) {
        is_need_load = true;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (is_need_load) {
            getShopList();
        } else {
            getShopList();
        }
        is_need_load = false;

    }

    public void getFavoriteAdd(List<FavoriteAddBean> item) {
        if (!Network.checkNetwork(getContext())) {
            ToastUtil.show(getContext(), "网络连接失败");
            return;
        }

        refresh.setRefreshing(true);

        Api.api_service.getFavoriteAdd(item).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        refresh.setRefreshing(false);
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    ToastUtil.makeText(getContext(), "添加成功");
                    StringBuilder builder = new StringBuilder();
                    for (int i = 0; i < item.size(); i++) {
                        builder.append(item.get(i).goods_id);
                        builder.append(",");
                    }
                    getCateDelete(builder.substring(0, builder.length() - 1),false);
//                    getShopList();
                });
    }

    public void getShopList() {
        if (!Network.checkNetwork(getContext())) {
            ToastUtil.show(getContext(), "网络连接失败");
            return;
        }

        refresh.setRefreshing(true);
        Api.api_service.getShopList().compose(RxLifeUtil.NocheckOn(this)).
                doFinally(() -> {
                    try {
                        refresh.setRefreshing(false);
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (result.code.equals("00")) {
                        goodBean = result;
                        if (goodBean.datas == null || goodBean.datas.size() == 0) {
                            layoutEmpty.setVisibility(View.VISIBLE);
                            layoutTotal.setVisibility(View.GONE);
                            txtRight.setVisibility(View.GONE);
                        } else {
//                            拆分失效跟未失效的数据
                            shixiaoList.clear();
                            for (int i = 0; i < goodBean.datas.size(); i++) {
                                for (int j = 0; j < goodBean.datas.get(i).items.size(); j++) {
                                    if (goodBean.datas.get(i).items.get(j).status.equals("0")) {
                                        shixiaoList.add(goodBean.datas.get(i).items.get(j));
                                        goodBean.datas.get(i).items.remove(j);
                                        j--;
                                    }
                                }
                                if (goodBean.datas.get(i).items.size() == 0) {
                                    goodBean.datas.remove(i);
                                    i--;
                                }
                            }
                            if (shixiaoList.size() != 0) {
                                txtShixiaoNum.setText("失效宝贝" + shixiaoList.size() + "件");
                                layoutShixiao.setVisibility(View.VISIBLE);
                                shopCartShiXiaoAdapter.update(shixiaoList);
                            } else {
                                layoutShixiao.setVisibility(View.GONE);
                            }

                            mBtnBuy.setText("结算");
                            mTvAllMoney.setText("¥");
                            mCbSelectAll.setChecked(false);
                            cbSelectAllSec.setChecked(false);
                            layoutEmpty.setVisibility(View.GONE);
                            layoutTotal.setVisibility(View.VISIBLE);
                            txtRight.setVisibility(View.VISIBLE);
                            mAdapter = new ExpandableListAdapter(getContext(), goodBean);
                            mAdapter.setChangedListener(this);
                            mExpandableListView.setAdapter(mAdapter);
                            //展开所有的分组
                            for (int i = 0; i < goodBean.getContent().size(); i++) {
                                mExpandableListView.expandGroup(i);
                            }
                        }
                    } else {
                        layoutEmpty.setVisibility(View.VISIBLE);
                        layoutTotal.setVisibility(View.GONE);
                        txtRight.setVisibility(View.GONE);
                    }


                });
    }

    public void getCateDelete(String id, boolean isShow) {
        if (!Network.checkNetwork(getContext())) {
            ToastUtil.show(getContext(), "网络连接失败");
            return;
        }

        ShopDeleteBean bean = new ShopDeleteBean();

        bean.id = id;
        Api.api_service.getShopDelete(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        refresh.setRefreshing(false);
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if(isShow){
                        ToastUtil.makeText(getContext(), "删除成功");
                    }
                    getShopList();
                });
    }

    @OnClick({R.id.cb_select_all, R.id.btn_settlement})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.cb_select_all:
                selectAll();
                break;
            case R.id.btn_settlement:
                if (mAdapter.getBuyList().items == null || mAdapter.getBuyList().items.size() == 0) {
                    ToastUtil.makeText(getContext(), "请选择要结算的商品");
                    return;
                }
                Intent intent = new Intent(getActivity(), SureOrderActivity.class);
                intent.putExtra("data", mAdapter.getBuyList());
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;
        }
    }

    @Override
    public void update(boolean isAllSelected, int count, double price) {
        mBtnBuy.setText("结算(" + count + ")");

        mTvAllMoney.setText("¥" + Arith.save(price));
        mCbSelectAll.setChecked(isAllSelected);
        cbSelectAllSec.setChecked(isAllSelected);
    }

    @OnClick({R.id.btn_clear_shixiao, R.id.btn_go_shop, R.id.txt_right, R.id.cb_select_all_sec, R.id.btn_add_collection, R.id.btn_delete})
    public void onViewClicked1(View view) {
        if (UI.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.btn_clear_shixiao:
                Dialog.showDefaultDialog(getContext(), "", "确定删除失效商品吗？", "我再想想", "删除", false, new Dialog.DialogDefaultClickListener() {
                    @Override
                    public void confirm() {
                        getCateDelete(shopCartShiXiaoAdapter.getShiXiaoId(),true);
                    }

                    @Override
                    public void cancel() {

                    }
                });
                break;
            case R.id.btn_go_shop:
                ((BussinessMainActivity) getActivity()).setFragmentChange(0);
                break;
            case R.id.cb_select_all_sec:
                selectAllSec();
                break;
            case R.id.txt_right:
                if (UI.toString(txtRight).equals("编辑")) {
                    layoutEdit.setVisibility(View.VISIBLE);
                    layoutBuy.setVisibility(View.GONE);
                    txtRight.setText("完成");
                } else if (UI.toString(txtRight).equals("完成")) {
                    layoutEdit.setVisibility(View.GONE);
                    layoutBuy.setVisibility(View.VISIBLE);
                    txtRight.setText("编辑");
                }
                break;
            case R.id.btn_add_collection:
                if (mAdapter.getCollections() == null || mAdapter.getCollections().size() == 0) {
                    ToastUtil.makeText(getContext(), "请选择要加入收藏的商品");
                    return;
                }
                getFavoriteAdd(mAdapter.getCollections());

                break;
            case R.id.btn_delete:
                if (TextUtils.isEmpty(mAdapter.getGoodsId())) {
                    ToastUtil.makeText(getContext(), "请选择要删除的商品");
                    return;
                }
                Dialog.showDefaultDialog(getContext(), "", "确定删除该商品吗？", "我再想想", "残忍删除", false, new Dialog.DialogDefaultClickListener() {
                    @Override
                    public void confirm() {
                        getCateDelete(mAdapter.getGoodsId(),true);
                    }

                    @Override
                    public void cancel() {

                    }
                });

                break;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
//        unbinder.unbind();
    }
}
